#include "thread_pool.h"

void getsCommand(task_t* task)
{
    printf("execute gets command.\n");

    char *data=task->data;
    int sockfd=task->peerfd;

    struct stat st;
    memset(&st,0,sizeof(st));

    int ret= stat(data,&st);
    if(ret==-1){
        perror("stat");
        return;
    }

    if(!S_ISREG(st.st_mode)){
        perror("not regular file");
        return;
    }

    //进行文件的发送
    char*filename=task->data;
    train_t t;
    memset(&t, 0, sizeof(t));
    
    //2. 读取文件内容( 相对路径 )
    int fd = open(filename, O_RDWR);
    if(fd==-1){
        perror("fopen");
        return;
    }
    memset(&t, 0, sizeof(t));
    
    //2.1 获取文件的长度
    struct stat fileInfo;
    memset(&fileInfo, 0, sizeof(fileInfo));
    fstat(fd, &fileInfo);
    off_t length = fileInfo.st_size;
    printf("file length: %ld\n", length);

    //发送文件的长度
    sendn(sockfd, &length, sizeof(length));
    printf("send length success\n");
    //根据文件长度确定传输的方式
    off_t threshold =100*1024*1024;
    if(length<threshold){
        //小文件传输
        while(1){
            memset(t.buff,0,sizeof(t.buff));
            int ret=read(fd,t.buff,sizeof(t.buff));
            if(ret==0){
                //文件读取完了
                break;
            }
            t.len=ret;
            printf("before sendn %s\n",t.buff);
            ret=send(sockfd,&t,4+t.len,0);
            if(ret==-1){
                break;
            }else if(ret==0){
                break;
            }
        }
        printf("send all of the file\n");
    }else{
        //大文件传输

        //借助于一条管道来搬运数据
        int fds[2];
        int ret = -1;
        int curSize = 0;
        pipe(fds);

        //发送文件内容
        while(curSize < length) {
            ret = splice(fd, NULL, fds[1], NULL,
                         4096, SPLICE_F_MORE);
            ret = splice(fds[0], NULL, sockfd, NULL,
                         ret, SPLICE_F_MORE);
            curSize += ret;
        }
        printf("curSize:%d\n", curSize);
        close(fd);
    }
}
